package ihm.views.main.catalog;

import ihm.models.ATKlistener;
import ihm.models.ATKmodel;
import ihm.models.events.CharacterChangedEvent;
import ihm.models.events.EquipmentChangedEvent;
import ihm.models.events.ItemTypeChangedEvent;
import ihm.models.events.LanguageChangedEvent;
import ihm.models.events.QueryChangedEvent;
import ihm.models.events.StatChangedEvent;

import java.awt.BorderLayout;
import java.sql.ResultSet;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import systems.database.DataBaseHandler;
import systems.exceptions.database.NotConnectedException;
import systems.exceptions.database.StatementIsNullException;
import systems.rpgBuilder.Item;

public class CatalogPanel extends JPanel implements ATKlistener{

  private static final long serialVersionUID = 1L;
  private FilterBar filterBar;
  private CatalogTable catalogTable;
  private JScrollPane scrollPane;
  private ATKmodel model;
  
  public CatalogPanel(ATKmodel model)
  {
    super(new BorderLayout());
    
    this.model = model;
    
    //Adding to the ATK listener
    //model.addATKlistener(this);
    
    filterBar = new FilterBar(model);
    catalogTable = new CatalogTable(model);
    scrollPane = new JScrollPane(catalogTable);
    
    this.add(filterBar, BorderLayout.NORTH);
    this.add(scrollPane, BorderLayout.CENTER);
  }

  @Override
  public void EquipmentChanged(EquipmentChangedEvent event) {
    //Nothing to do
  }

  @Override
  public void ItemTypeChanged(ItemTypeChangedEvent event) {
    Item item = event.getItemSelected();
    filterBar.updateType(item.getItemTypesList());
  }

  @Override
  public void LanguageChanged(LanguageChangedEvent event) {
    filterBar.updateFilterBar();
    catalogTable.updateColumnsNameModel();
    if(catalogTable.getRowCount()>0)
      QueryChanged(new QueryChangedEvent(this, model.getQuery()));
  }

  @Override
  public void QueryChanged(QueryChangedEvent event) {
    try {
      String query = event.getQuery().getString();
      //System.out.println("Query : "+query);
      ResultSet result = DataBaseHandler.query(query);
      catalogTable.buildRows(result);
      catalogTable.updateColumnsNameModel();
    } catch (NotConnectedException e) {
      e.printStackTrace();
    } catch (StatementIsNullException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void StatChanged(StatChangedEvent event) {
    // Nothing here
  }

  @Override
  public void CharacterChanged(CharacterChangedEvent event) {
    // Nothing here
  }
}
